/*******************************************************************************
 * Package: com.hngtrust.iir.report.service.impl
 * Type:    ReportPushServiceImpl
 * Date:    2021/3/30 10:09
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.report.service.impl;

import com.hngtrust.clickhouse.report.dto.SourceAgencyDTO;
import com.hngtrust.clickhouse.report.entity.AppReport;
import com.hngtrust.clickhouse.report.dto.ListReportPushDTO;
import com.hngtrust.clickhouse.report.service.AppReportService;
import com.hngtrust.framework.page.PageParam;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.iir.base.service.DictService;
import com.hngtrust.iir.base.service.IndustryService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.report.controller.dto.ListReportRespVO;
import com.hngtrust.iir.report.controller.dto.QuerySourceAgencyReqVO;
import com.hngtrust.iir.report.service.ReportPushService;
import com.hngtrust.iir.report.controller.dto.ListReportPushSchemeRespVO;
import com.hngtrust.iir.report.service.ReportSchemeConfigService;
import com.hngtrust.iir.user.entity.TagRel;
import com.hngtrust.iir.user.service.TagRelService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 推送研报接口实现类
 *
 * @author Keqiwei
 * @date 2021/3/30 10:09
 */

@Service
public class ReportPushServiceImpl implements ReportPushService {
   
    @Autowired
    private ReportSchemeConfigService schemeConfigService;
    
    @Autowired
    private DictService dictService;
    
    @Autowired
    private PageService pageService;
    
    @Autowired
    private IndustryService industryService;
    
    @Autowired
    private AppReportService reportService;
    
    @Autowired
    private TagRelService tagRelService;
   
   
    
    
    /**
     * 根据推送策略推送研报
     * @param listPushScheme
     * @param pageParam
     * @return
     */
    public List<ListReportRespVO> getReportSchemeRespVOS(ListReportPushSchemeRespVO listPushScheme, PageParam pageParam) {
        ListReportPushDTO reportPushDTO = new ListReportPushDTO();
        BeanUtils.copyProperties(listPushScheme, reportPushDTO);
        PageResult<AppReport> page = pageService.page(pageParam, () -> reportService.queryListReport(reportPushDTO));
        List<ListReportRespVO> reports = new ArrayList<>();
        for (AppReport report:page.getRows()) {
            ListReportRespVO respVO = new ListReportRespVO();
            BeanUtils.copyProperties(report,respVO);
            TagRel tagRel = new TagRel();
            tagRel.setDataType(Constant.TAG_DATATYPE_REPORT);
            tagRel.setDataId(report.getId());
            respVO.setLabels(tagRelService.queryList(tagRel));
            reports.add(respVO);
        }
        return reports;
    }
    
    
    /**
     * 去重方法
     */
    public  <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
    
    @Override
    public PageResult<SourceAgencyDTO> querySourceAgency(ReqDTO<QuerySourceAgencyReqVO> dto) {
        String source = null;
        if (!dto.getContent().getName().isEmpty() && null != dto.getContent().getName()){
            source = "%"+dto.getContent().getName()+"%";
        }
    
    
        String s = source;
        PageResult<SourceAgencyDTO> page = pageService.page(dto.getPageParam(),()-> reportService.querySourceAgency(s));
        page.getRows().forEach(ss->{
            String letter = chineseToFirstLetter(ss.getName()).substring(0,1);
            ss.setLetter(letter);
            ss.setCode(letter+ss.getCount());
        });
        List<SourceAgencyDTO> collect = page.getRows().stream().sorted(Comparator.comparing(SourceAgencyDTO::getCode))
                .collect(Collectors.toList());
        List<SourceAgencyDTO> rows = collect;
        if (!dto.getContent().getCode().isEmpty() && null != dto.getContent().getCode()){
            rows = new ArrayList<>();
            for (String s1 : dto.getContent().getCode()) {
                rows.addAll(collect.stream().filter(c->{
                    if (c.getLetter().equals(s1)){
                        return true;
                    }else {
                        return false;
                    }
                }).collect(Collectors.toList()));
            }
            rows = rows.stream().sorted(Comparator.comparing(SourceAgencyDTO::getCode)).collect(Collectors.toList());
        }
        page.setRows(rows);
        return page;
    }
    
    
    public static String chineseToFirstLetter(String c) {
        String string = "";
        char b;
        int a = c.length();
        for (int k = 0; k < a; k++) {
            b = c.charAt(k);
            String d = String.valueOf(b);
            String str = converterToFirstSpell(d);
            String s = str.toUpperCase();
            String g = s;
            char h;
            int j = g.length();
            for (int y = 0; y <= 0; y++) {
                h = g.charAt(0);
                string += h;
            }
        }
        return string;
    }
    
    public static String converterToFirstSpell(String chines) {
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            String s = String.valueOf(nameChar[i]);
            if (s.matches("[\\u4e00-\\u9fa5]")) {
                try {
                    String[] mPinyinArray = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
                    pinyinName += mPinyinArray[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }
}
